//
//  HRZUserCollectManager.m
//  EMarket
//
//  Created by 石头 on 2018/5/23.
//  Copyright © 2018 好日子. All rights reserved.
//

#import "HRZUserCollectManager.h"

// Controllers

// Models
#import "HRZGoodsModel.h"
// Views

// Vendors

// Categories
#import <FMDB.h>
// Others

@interface HRZUserCollectManager ()
{
    FMDatabase *_db;
}

@end



@implementation HRZUserCollectManager

+ (instancetype)shareDefaultManager {
    static HRZUserCollectManager *_collectMgr = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _collectMgr = [[HRZUserCollectManager alloc] init];
        [_collectMgr initWithBase];
    });
    return _collectMgr;
}

- (void)initWithBase {
    /** document Path */
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    /** file Path */
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"collect.sqlite"];
    
    /** 实例化FMDataBase */
    _db = [FMDatabase databaseWithPath:filePath];
    
    /** 初始化table */
    [_db open];
    NSString *personSql = @"CREATE TABLE 'collect' ('id' INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL ,'collect_id' VARCHAR(255),'goodsName' VARCHAR(255),'goodsId' VARCHAR(255))";
    [_db executeUpdate:personSql];
    [_db close];
}

- (void)addCollectGoods:(HRZGoodsModel *)goods {
    [_db open];
    
    NSNumber *maxID = @(0);
    
    FMResultSet *res = [_db executeQuery:@"SELECT * FROM collect"];
    
    while ([res next]) {
        if ([maxID integerValue] < [[res stringForColumn:@"collect_id"] integerValue]) {
            maxID = @([[res stringForColumn:@"collect_id"] integerValue]);
        }
    }
    
    maxID = @([maxID integerValue] + 1);
    
    [_db executeUpdate:@"INSERT INTO collect(collect_id,goodsName,goodsId)VALUES(?,?,?)",maxID,goods.goodsName,goods.goodsId];
    
    [_db close];
}

- (void)removeCollectGoods:(HRZGoodsModel *)goods {
    [_db open];
    
    [_db executeUpdate:@"DELETE FROM collect WHERE goodsId = ?",goods.goodsId];
    
    [_db close];
}

- (BOOL)isUserCollectGoods:(HRZGoodsModel *)goods {
    
    FMResultSet *res = [_db executeQuery:@"SELECT * FROM collect"];
    
    while ([res next]) {
        if ([goods.goodsId isEqualToString:[res stringForColumn:@"goodsId"]]) {
            return YES;
        }
    }
    return NO;
}

- (NSArray *)allUserCollectGoods {
    
    return nil;
}

@end
